//
//  DBStorageHelper.m
//  IsolatedStorageDB
//
//  Created by Fanty on 13-12-17.
//  Copyright (c) 2013年 Fanty. All rights reserved.
//

#import "DBStorageHelper.h"

#import "DBStorageUpdater.h"

#import "ChamleonJSON.h"
#import "ChamleonDB.h"


@interface DBStorageData()

@property(nonatomic,strong) NSString* moduleIdentifier;

@property(nonatomic,strong) NSString* dbName;

@property(nonatomic,strong) NSString* dbSource;

@property(nonatomic,strong) NSString* version;


-(NSString*)combinePath:(BOOL)newPath;

@end

@interface DBStorageHelper()

@property(nonatomic,strong) NSMutableArray* list;

@end

@implementation DBStorageData

-(ChamleonDB*)openDatabase{
    ChamleonDB* db=[ChamleonDB databaseWithPath:[self combinePath:YES]];
    
    return db;
}

-(NSString*)combinePath:(BOOL)newPath{
    NSString* root=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    root=[root stringByAppendingPathComponent:@"dbStorage"];
    if(newPath && ![[NSFileManager defaultManager] fileExistsAtPath:root])
        [[NSFileManager defaultManager] createDirectoryAtPath:root withIntermediateDirectories:YES attributes:Nil error:nil];

    root=[root stringByAppendingPathComponent:self.moduleIdentifier];
    if(newPath && ![[NSFileManager defaultManager] fileExistsAtPath:root])
        [[NSFileManager defaultManager] createDirectoryAtPath:root withIntermediateDirectories:YES attributes:Nil error:nil];

    if([self.identifier length]>0){
        root=[root stringByAppendingPathComponent:self.identifier];
        if(newPath && ![[NSFileManager defaultManager] fileExistsAtPath:root])
            [[NSFileManager defaultManager] createDirectoryAtPath:root withIntermediateDirectories:YES attributes:Nil error:nil];
    }
    
    NSString* dbPath=[root stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",self.dbName]];
    NSString* versionPath=[root stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_version.bat",self.dbName]];
    
    if(newPath && ![[NSFileManager defaultManager] fileExistsAtPath:dbPath]){
        NSString* path=[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@.bundle/data/%@",self.moduleIdentifier,self.dbSource] ofType:nil];

        [[NSFileManager defaultManager] copyItemAtPath:path toPath:dbPath error:nil];
        
        [self.version writeToFile:versionPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    if(newPath){
        NSString* currentVersion=[NSString stringWithContentsOfFile:versionPath encoding:NSUTF8StringEncoding error:nil];
        
        if(![currentVersion isEqualToString:self.version]){
            [self updateDatabase];
            [self.version writeToFile:versionPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        }
        
    }
    
    return dbPath;
    
}

-(BOOL)existsDatabase{
    return [[NSFileManager defaultManager] fileExistsAtPath:[self combinePath:NO]];
}

-(void)removeDatabase{
    [[NSFileManager defaultManager] removeItemAtPath:[self combinePath:NO] error:nil];
}

-(void)updateDatabase{
    NSString* newDatabase=[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@.bundle/data/%@",self.moduleIdentifier,self.dbSource] ofType:nil];
    
    NSString* originDatabase=[self combinePath:NO];
    
    [DBStorageUpdater createNewTable:originDatabase newDB:newDatabase];

}

-(NSString*)newVersion{
    return self.version;
}

-(NSString*)currentVersion{
    return @"";
}



@end

@implementation DBStorageHelper

+(id)standandStorage{
    static DBStorageHelper *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[DBStorageHelper alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}

-(id)init{
    self=[super init];
    if(self){
        self.list=[[NSMutableArray alloc] initWithCapacity:2];
    }
    return self;
}

-(void)configStorageWithModule:(NSString*)moduleIdentifier{
    NSString* path=[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@.bundle/data/dbStorage",moduleIdentifier] ofType:@"json"];
    
    NSString* data=[[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    if([data length]>2){
        id obj=[data JSONObject];
        
        DBStorageData* storage=[[DBStorageData alloc] init];
        storage.moduleIdentifier=moduleIdentifier;
        storage.dbName=[obj objectForKey:@"dbName"];
        storage.version=[obj objectForKey:@"version"];
        storage.dbSource=[obj objectForKey:@"db_source"];
        
        [self.list addObject:storage];
        
        
    }
}

-(DBStorageData*)storageDataWithModuleIdentifier:(NSString*)moduleIdentifier{
    for(DBStorageData* data in self.list){
        if([data.moduleIdentifier isEqualToString:moduleIdentifier])
            return data;
    }
    return nil;
}


@end
